package com.yfbao.horizon.inspection.service.impl;

import com.yfbao.horizon.inspection.config.InspectConfig;
import com.yfbao.horizon.inspection.config.ReportTaskConfig;
import com.yfbao.horizon.inspection.dto.ReportDto;
import com.yfbao.horizon.inspection.dto.ReportInfoResult;
import com.yfbao.horizon.inspection.entity.SystemInspectRecord;
import com.yfbao.horizon.inspection.engine.InspectEngine;
import com.yfbao.horizon.inspection.engine.impl.LifeCycleEngine;
import com.yfbao.horizon.inspection.engine.impl.MetricsCollectorEngine;
import com.yfbao.horizon.inspection.engine.impl.ReportGeneratorEngine;
import com.yfbao.horizon.inspection.repository.SystemInspectRecordRepository;
import com.yfbao.horizon.inspection.service.InspectionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 巡检系统服务实现类
 * 实现巡检系统的核心业务逻辑
 */
@Service
@Transactional
public class InspectionServiceImpl implements InspectionService {

    private static final Logger logger = LoggerFactory.getLogger(InspectionServiceImpl.class);

    @Autowired
    private SystemInspectRecordRepository recordRepository;

    @Autowired
    private ReportGeneratorEngine reportGeneratorEngine;

    @Autowired
    private MetricsCollectorEngine metricsCollectorEngine;

    @Autowired
    private LifeCycleEngine lifeCycleEngine;

    /**
     * 引擎映射，用于根据编码获取对应的引擎实例
     */
    private final Map<String, InspectEngine<?>> engineMap = new ConcurrentHashMap<>();

    /**
     * 初始化引擎映射
     */
    @PostConstruct
    public void init() {
        engineMap.put(reportGeneratorEngine.getCode(), reportGeneratorEngine);
        engineMap.put(metricsCollectorEngine.getCode(), metricsCollectorEngine);
        engineMap.put(lifeCycleEngine.getCode(), lifeCycleEngine);
        logger.info("巡检引擎初始化完成，已注册 {} 个引擎", engineMap.size());
    }

    @Override
    public ReportDto executeInspectionTask(InspectConfig config, ReportTaskConfig reportConfig) {
        logger.info("执行巡检任务，配置: {}, 报告配置: {}", config, reportConfig);
        
        // 选择合适的引擎执行巡检任务
        InspectEngine<?> engine = selectEngineForTask(config);
        if (engine != null) {
            return engine.inspectReportResult(config, reportConfig);
        }
        
        // 默认使用报告生成引擎
        return reportGeneratorEngine.inspectReportResult(config, reportConfig);
    }

    @Override
    public ReportDto executeCustomInspectionTask(InspectConfig config, ReportTaskConfig reportConfig) {
        logger.info("执行自定义巡检任务，配置: {}, 报告配置: {}", config, reportConfig);
        
        // 选择合适的引擎执行自定义巡检任务
        InspectEngine<?> engine = selectEngineForTask(config);
        if (engine != null) {
            return engine.inspectCustomerReportResult(config, reportConfig);
        }
        
        // 默认使用报告生成引擎
        return reportGeneratorEngine.inspectCustomerReportResult(config, reportConfig);
    }

    @Override
    public SystemInspectRecord collectInspectionMetrics(InspectConfig config) {
        logger.info("采集巡检指标，配置: {}", config);
        
        // 选择合适的引擎执行指标采集
        InspectEngine<?> engine = selectEngineForTask(config);
        if (engine != null) {
            return engine.inspectCollect(config);
        }
        
        // 默认使用指标采集引擎
        return metricsCollectorEngine.inspectCollect(config);
    }

    @Override
    public SystemInspectRecord collectCustomInspectionMetrics(InspectConfig config) {
        logger.info("采集自定义巡检指标，配置: {}", config);
        
        // 选择合适的引擎执行自定义指标采集
        InspectEngine<?> engine = selectEngineForTask(config);
        if (engine != null) {
            return engine.inspectCustomerCollect(config);
        }
        
        // 默认使用指标采集引擎
        return metricsCollectorEngine.inspectCustomerCollect(config);
    }

    @Override
    public void executePeriodicScan(InspectConfig config) {
        logger.info("执行周期扫描，配置: {}", config);
        
        // 选择合适的引擎执行周期扫描
        InspectEngine<?> engine = selectEngineForTask(config);
        if (engine != null) {
            engine.inspectPeriodScan(config);
        } else {
            // 默认使用指标采集引擎
            metricsCollectorEngine.inspectPeriodScan(config);
        }
    }

    @Override
    public List<ReportInfoResult> getReportInfo(String taskNo) {
        logger.info("获取巡检报告详情，任务编号: {}", taskNo);
        
        // 尝试从各个引擎获取报告详情
        for (InspectEngine<?> engine : engineMap.values()) {
            try {
                @SuppressWarnings("unchecked")
                List<ReportInfoResult> results = (List<ReportInfoResult>) engine.getReportInfo(taskNo);
                if (results != null && !results.isEmpty()) {
                    return results;
                }
            } catch (Exception e) {
                logger.warn("从引擎 {} 获取报告详情失败", engine.getCode(), e);
            }
        }
        
        // 默认从报告生成引擎获取
        return reportGeneratorEngine.getReportInfo(taskNo);
    }

    @Override
    public SystemInspectRecord saveInspectionRecord(SystemInspectRecord record) {
        logger.info("保存巡检记录，环境: {}, 分类: {}, 检测项: {}", 
                record.getInspectEnv(), record.getInspectCategory(), record.getInspectItem());
        
        return recordRepository.save(record);
    }

    @Override
    @Transactional
    public List<SystemInspectRecord> batchSaveInspectionRecords(List<SystemInspectRecord> records) {
        logger.info("批量保存巡检记录，数量: {}", records.size());
        
        return recordRepository.saveAll(records);
    }

    @Override
    public List<SystemInspectRecord> findRecordsByEnvAndCategory(String inspectEnv, String inspectCategory) {
        logger.info("查询巡检记录，环境: {}, 分类: {}", inspectEnv, inspectCategory);
        
        return recordRepository.findByInspectEnvAndInspectCategory(inspectEnv, inspectCategory);
    }

    @Override
    public List<SystemInspectRecord> findRecordsByInspectItem(String inspectItem) {
        logger.info("查询巡检记录，检测项: {}", inspectItem);
        
        return recordRepository.findByInspectItem(inspectItem);
    }

    @Override
    public List<SystemInspectRecord> findRecordsByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        logger.info("查询巡检记录，时间范围: {} - {}", startTime, endTime);
        
        return recordRepository.findByCollectTimeBetween(startTime, endTime);
    }

    @Override
    @Transactional
    public int deleteExpiredRecords(LocalDateTime expireTime) {
        logger.info("删除过期巡检记录，过期时间: {}", expireTime);
        
        List<SystemInspectRecord> expiredRecords = recordRepository.findByCollectTimeBefore(expireTime);
        int count = expiredRecords.size();
        
        if (count > 0) {
            recordRepository.deleteAll(expiredRecords);
            logger.info("已删除 {} 条过期巡检记录", count);
        }
        
        return count;
    }

    @Override
    @Transactional
    public int deleteExpiredRecordsByEnv(String inspectEnv, LocalDateTime expireTime) {
        logger.info("删除过期巡检记录，环境: {}, 过期时间: {}", inspectEnv, expireTime);
        
        int count = recordRepository.deleteByInspectEnvAndCollectTimeBefore(inspectEnv, expireTime);
        logger.info("已删除环境 {} 的 {} 条过期巡检记录", inspectEnv, count);
        
        return count;
    }

    @Override
    @Transactional
    public int deleteExpiredRecordsByCategory(String inspectCategory, LocalDateTime expireTime) {
        logger.info("删除过期巡检记录，分类: {}, 过期时间: {}", inspectCategory, expireTime);
        
        int count = recordRepository.deleteByInspectCategoryAndCollectTimeBefore(inspectCategory, expireTime);
        logger.info("已删除分类 {} 的 {} 条过期巡检记录", inspectCategory, count);
        
        return count;
    }

    @Override
    public Map<String, Object> getInspectionStatistics(String inspectEnv, String inspectCategory, LocalDateTime startTime, LocalDateTime endTime) {
        logger.info("获取巡检统计信息，环境: {}, 分类: {}, 时间范围: {} - {}", 
                inspectEnv, inspectCategory, startTime, endTime);
        
        Map<String, Object> statistics = new HashMap<>();
//        List<SystemInspectRecord> records;
//
//        // 根据参数查询记录
//        if (inspectEnv != null && inspectCategory != null) {
//            records = recordRepository.findByInspectEnvAndInspectCategory(inspectEnv, inspectCategory);
//        } else if (inspectItem != null) {
//            records = recordRepository.findByInspectItem(inspectItem);
//        } else {
//            records = recordRepository.findAll();
//        }
//
//        // 统计结果
//        long totalRecords = records.size();
//        long normalCount = records.stream().filter(r -> "normal".equals(r.getInspectItemResult())).count();
//        long middleCount = records.stream().filter(r -> "middle".equals(r.getInspectItemResult())).count();
//        long highCount = records.stream().filter(r -> "high".equals(r.getInspectItemResult())).count();
//
//        statistics.put("totalRecords", totalRecords);
//        statistics.put("normalCount", normalCount);
//        statistics.put("middleCount", middleCount);
//        statistics.put("highCount", highCount);
//        statistics.put("inspectEnv", inspectEnv);
//        statistics.put("inspectCategory", inspectCategory);
//        statistics.put("startTime", startTime);
//        statistics.put("endTime", endTime);
        
        return statistics;
    }

    @Override
    public List<String> getAllEngineCodes() {
        return new ArrayList<>(engineMap.keySet());
    }

    @Override
    public Object getEngineByCode(String engineCode) {
        return engineMap.get(engineCode);
    }

    /**
     * 根据任务配置选择合适的引擎
     * @param config 巡检配置
     * @return 合适的引擎实例或null
     */
    private InspectEngine<?> selectEngineForTask(InspectConfig config) {
        // 根据配置选择合适的引擎
        String category = config.getInspectCategory();
        if (category != null) {
            switch (category) {
                case "lifecycle":
                    return lifeCycleEngine;
                case "metrics":
                case "index":
                    return metricsCollectorEngine;
                case "report":
                    return reportGeneratorEngine;
                default:
                    break;
            }
        }
        
        // 根据检测项选择引擎
        String inspectItem = config.getInspectItem();
        if (inspectItem != null) {
            if (inspectItem.contains("metrics") || inspectItem.contains("index")) {
                return metricsCollectorEngine;
            } else if (inspectItem.contains("report")) {
                return reportGeneratorEngine;
            } else if (inspectItem.contains("lifecycle") || inspectItem.contains("cleanup")) {
                return lifeCycleEngine;
            }
        }
        
        return null;
    }

    // 修复getInspectionStatistics方法中的错误变量名
    private List<SystemInspectRecord> findRecordsByTimeRangeWithItem(String inspectEnv, String inspectCategory, String inspectItem, LocalDateTime startTime, LocalDateTime endTime) {
        if (inspectItem != null) {
            return recordRepository.findByInspectItem(inspectItem);
        }
        return recordRepository.findAll();
    }
}